package it.francescogabbrielli.android.solidalapp.actions;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.Constants;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.profileendpoint.Profileendpoint;
import it.francescogabbrielli.android.solidalapp.profileendpoint.model.Profile;

public class EndpointsGetProfile extends Action {

	private boolean loading;
	
	private Profile profile;
	
	@Override
	public void execute() throws Exception {
				 
		SharedPreferences prefs = context.getSharedPreferences(
				SolidalApp.class.getCanonicalName(), Context.MODE_PRIVATE);
		
		String id = prefs.getString(Constants.PROFILE_ACCOUNT, "");
		if ("".equals(id)) {
			// find account (XXX: temporary)
			AccountManager manager = AccountManager.get(context);
			for (Account account : manager.getAccounts()) {
				Log.i("Account: "+account.type, account.name);
				if ("com.google".equals(account.type)) {
					id = account.name;
					prefs.edit().putString(Constants.PROFILE_ACCOUNT, id).commit();
					break;
				}
			}
		}

		if ("".equals(id))
			throw new IllegalStateException("No account selected");
		
		loading = true;
		
		Profileendpoint endpoint = EndpointsUtils.buildEndpoint(Profileendpoint.class);
		profile = endpoint.getProfileByAccount(id).execute();
		setModel(profile);
		
	}

	@Override
	public void onPostExecute() throws Exception {
		SolidalApp app = (SolidalApp) context.getApplicationContext();
		Log.v(SolidalApp.TAG, "Received profile: "+profile);
		if (loading)
			if(profile!=null) {
				app.setData(DataKey.PROFILE, profile);
				app.registerToServices();
			} else if (app.getData(DataKey.PROFILE)==null) {
				start(context, EndpointsInsertProfile.class);
			}
	}

}
